package sust.cse.ruhul.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import sust.cse.ruhul.jobs1.Page2;
import sust.cse.ruhul.jobs1.Page_Location;
import sust.cse.ruhul.jobs1.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class JobList extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	private ListView passLstview;
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;
	
	private static byte[] buff =new byte[1024];
	private String retval="";
	
	private ArrayAdapter<String>	listAdapter;
	
	private int[] app_ids;
	private String[] app_time;
	private String[] app_orgname;
	private String[] app_finalstr;

	
	private static final String SOAP_ACTION = "http://tempuri.org/GetAllJobs";

    private static final String METHOD_NAME = "GetAllJobs";

    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://108.163.232.50:1100/LeewayWebService.asmx";
	
	public JobList(Activity activity,ListView passLstview) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.passLstview = passLstview;
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Search", "Updating",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {
		
		 try {

	            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

	            //request.addProperty("JobId", "3");

	            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	            envelope.dotNet=true;
	            envelope.setOutputSoapObject(request);

	            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
	            androidHttpTransport.call(SOAP_ACTION, envelope);
	            
	            SoapPrimitive resultSoapPrimitive;
	            resultSoapPrimitive = (SoapPrimitive) envelope.getResponse();
	                
	            String result = resultSoapPrimitive.toString();

	            retval = result;
	            
	            Log.d("return", retval);
	            
	            return retval;
	           
	        } catch (Exception e) {
	            
	       }
		 return retval;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		int loopcount;
		
		/*Toast toast = Toast.makeText(activity, result, Toast.LENGTH_SHORT);
		toast.show();*/
		
		Log.d("Post tt", result);
		progdialod.dismiss();
		
		Log.d("Post Exec", result);
		
		try {
			JSONArray appLink = new JSONArray(result);
			loopcount = appLink.length();
			app_ids = new int[appLink.length()];
			app_time = new String[appLink.length()];
			app_orgname = new String[appLink.length()];
			app_finalstr = new String[appLink.length()];

				for(int i=0;i<appLink.length();i++){
					JSONObject match = appLink.getJSONObject(i);
					app_ids[i] = Integer.parseInt(match.getString("Job_id"));
					app_time[i] = match.getString("Last_update_stamp");
					app_orgname[i] = match.getString("OrgName");
					String fixdate = fixDate(app_time[i].substring(0, 10));
					app_finalstr[i] = fixdate+" - "+app_orgname[i];
				}

		} catch (JSONException e) {
			e.printStackTrace();
		} 
		
		final ArrayList<String> planetList = new ArrayList<String>();
		planetList.addAll(Arrays.asList(app_finalstr));

		listAdapter = new ArrayAdapter<String>(activity, R.layout.row, app_finalstr);
		passLstview.setAdapter(listAdapter);
		passLstview.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int location,
					long arg3)
			{
				//final String item = listAdapter.getItem(arg2);
				
				
				final Intent intent = new Intent(activity, Page_Location.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle bundle = new Bundle();
				bundle.putInt("jobid", app_ids[location]);  
				bundle.putString("orgname", app_finalstr[location]);
				intent.putExtras(bundle);
				context.startActivity(intent);

			}
		});
		
	}

	public String fixDate(String inputDate){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date=null;
		try {
			date = sdf.parse(inputDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		sdf = new SimpleDateFormat("MMM dd, yyyy");
		String MMdd = sdf.format(date);
		
		Log.e("Formated Date", MMdd);
		
		return MMdd;
	}
	
}
